package cn.com.easy.sign;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import cn.com.easy.dto.MessageDTO;
import cn.com.easy.exception.BusinessException;
import cn.com.easy.utils.FastJSONUtils;
import cn.com.easy.utils.ResponseOutputUtils;

/**
 * 签名过滤器<br/>
 * 普通Servlet Filter与spring的controller所生产的session Id是不一样的，所以适配了一个spring 托管的filter
 * 
 * @author nibili 2017年9月1日
 * 
 */
public abstract class SignBaseSpringFilter extends OncePerRequestFilter {

	public abstract SignConfig getSignConfig(ServletRequest request, String appId) throws BusinessException, Exception;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

		// 转成参数对象
		@SuppressWarnings("unchecked")
		Map<String, String[]> requestParams = request.getParameterMap();
		// 获取支付宝POST过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}
		//
		String jsonString = FastJSONUtils.toJsonString(params);
		//
		SignBaseParamDto signBaseParamDto = FastJSONUtils.toObject(jsonString, SignBaseParamDto.class);
		//
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;

		// 一、验证 验证码
		// 如果是获取签名验证码，不需要验证验证码
		if (httpServletRequest.getRequestURI().indexOf("sign/captcha.json") > -1) {

		} else {
			try {
				if (SignCaptchaUtil.validCaptcha(httpServletRequest, signBaseParamDto) == false) {
					throw new BusinessException("验证码错误!");
				}
			} catch (BusinessException ex) {
				ResponseOutputUtils.renderJson(httpServletResponse, MessageDTO.newInstance("", false, ex.getLocalizedMessage()));
				return;
			}
		}

		// 签名所需配置
		SignConfig signConfig = null;
		try {
			if (StringUtils.isBlank(signBaseParamDto.getAppId()) == true) {
				throw new BusinessException("appId不能为空");
			}
			signConfig = this.getSignConfig(request, signBaseParamDto.getAppId());
			if (signConfig == null) {
				throw new BusinessException("appId配置无效");
			}
		} catch (BusinessException ex) {
			ResponseOutputUtils.renderJson(httpServletResponse, MessageDTO.newInstance("", false, ex.getLocalizedMessage()));
			return;
		} catch (Exception ex) {
			ex.printStackTrace();
			ResponseOutputUtils.renderJson(httpServletResponse, MessageDTO.newInstance("", false, "获取签名配置失败"));
			return;
		}
		// 二、校验签名
		try {
			boolean resBoolean = HttpServletRequestSignUtils.very(httpServletRequest, signConfig.getPublicKey());
			if (resBoolean == true) {
				filterChain.doFilter(httpServletRequest, httpServletResponse);
			} else {
				ResponseOutputUtils.renderJson(httpServletResponse, MessageDTO.newInstance("", false, "签名校验失败"));
			}
			return;
		} catch (BusinessException ex) {
			ResponseOutputUtils.renderJson(httpServletResponse, MessageDTO.newInstance("", false, ex.getLocalizedMessage()));
		} catch (Exception ex) {
			ex.printStackTrace();
			ResponseOutputUtils.renderJson(httpServletResponse, MessageDTO.newInstance("", false, "检名校验发内部错误，请稍后再试"));
		}

	}

}
